"use strict";
const mvc = require('cosjs.mvc');
const seasonID = 1001;
/**
 * @name arena
 * 竞技场相关
 */

/**
 * @name setupPvpTeam
 * @param string teamListID 队伍ID
 * 修改防守阵容
 */
exports.setupPvpTeam = async function () {
    let teamListID = this.get('teamListID', 'string');
    if (!teamListID) {
        return this.quick_error('M2saghge140', ' 参数错误');
    }
    this.updater.role.key("team." + teamListID);
    await this.updater.data();
    let teamData = this.updater.role.get("team." + teamListID);
    if (!teamData) {
        return this.quick_error("M2saghge40", "队伍数据不存在", teamListID);
    }
    this.updater.role.set("pvpS.defend", teamListID);
    return this.updater.save()
}

/**
 * @name data
 * 对手列表
 * @param string fields 需要额外获取玩家的基本信息
 * @tip 结果：[uid,分数，是否已经干翻，位置]
 */
exports.data = async function () {
    let playerRedis = this.model.redis("ladder/player", this.sid);
    return playerRedis.get(this.uid).then(async ret => {
        if (!ret) {
            //对手不存在,获取新的对手列表
            let res = await this.library('ladder/getPlayer');
            let playerList = [];
            for (let k in res) {
                playerList.push(res[k]);
            }
            return playerList;
        }
        else {
            if (ret[5]) {
                delete ret[5];
            }
            let playerList = [];
            let num = 0;
            for (let k in ret) {
                playerList.push(ret[k]);
                if (ret[k].flag != 0) {
                    num++
                }
            }
            //如果已经干翻了5个人，就重新获取
            if (num == 5) {
                let res = await this.library('ladder/getPlayer');
                let playerListNew = [];
                for (let k in res) {
                    playerListNew.push(res[k]);
                }
                return playerListNew;
            }
            return playerList;
        }
    });
}


/**
 * @name refresh
 * 手动刷新对手
 */
exports.refresh = async function () {
    //判断赛季是否开放
    const arena3V3SeasonStart = this.config('base', 'arena3V3SeasonStart').strVal;
    const arena3V3RoundTime = this.config('base', 'arena3V3RoundTime').val; // 赛季战斗时长，单位小时
    const arena3V3ResultTime = this.config('base', 'arena3V3ResultTime').val; // 赛季结算时长，单位小时
    let { beginTIme, endTIme, currentSeason } = getSeasonTimes(arena3V3SeasonStart, arena3V3RoundTime, arena3V3ResultTime);
    if (this.updater.time < beginTIme || this.updater.time > endTIme) {
        return this.quick_error("M2saghge40", "竞技场赛季未开放", seasonID);
    }
    let arenaConfig = this.config('arenaConfig', seasonID);
    if (!arenaConfig) {
        return this.quick_error("M2saghge40", "竞技场数据不存在", seasonID);
    }
    let ty = this.updater.item.types(arenaConfig['refreshItem']);
    this.updater.item.key(ty._id);
    await this.updater.data();
    this.updater.sub(arenaConfig['refreshItem'], 1);
    await this.updater.save();
    return this.library('ladder/getPlayer');
}



/**
 * @name startBattle
 * @param string uid 对手ID
 * @tip 主线通关记录在role.stage里
 * 创建pvp战斗
 */
exports.startBattle = async function () {
    let id = this.get('uid', 'string');
    if (!id) {
        return this.quick_error('N2BS1', "参数缺失");
    }
    //判断赛季是否开放
    let battleData = { "battleUid": id, "flag": false, "arenaDataID": seasonID }
    let battleCache = this.model.redis("battleCache", this.sid);
    const arena3V3SeasonStart = this.config('base', 'arena3V3SeasonStart').strVal;
    const arena3V3RoundTime = this.config('base', 'arena3V3RoundTime').val; // 赛季战斗时长，单位小时
    const arena3V3ResultTime = this.config('base', 'arena3V3ResultTime').val; // 赛季结算时长，单位小时
    let { beginTIme, endTIme, currentSeason, phase } = getSeasonTimes(arena3V3SeasonStart, arena3V3RoundTime, arena3V3ResultTime);
    if (this.updater.time < beginTIme || this.updater.time > endTIme) {
        return this.quick_error("M2saghge40", "竞技场赛季未开放", seasonID);
    }
    if (phase == 0) {
        return this.quick_error("M2saghge40", "赛季结算中", seasonID);
    }
    let arenaConfig = this.config('arenaConfig', seasonID);
    if (!arenaConfig) {
        return this.quick_error("M2saghge40", "竞技场数据不存在", seasonID);
    }
    let ty = this.updater.item.types(arenaConfig['battleItem']);
    this.updater.item.key(ty._id);
    this.updater.role.key('pvpS.ID');
    await this.updater.data();
    let seasonIDBase = this.updater.role.get('pvpS.ID') || 0;
    if (currentSeason != seasonIDBase) {
        this.updater.role.set("pvpS.ID", currentSeason);
    }
    //扣除次数
    this.updater.sub(arenaConfig['battleItem'], 1);
    await this.updater.save();
    //判断对手是否正确
    let playerRedis = this.model.redis("ladder/player", this.sid);
    let playerList = await playerRedis.get(this.uid);
    let flag = 0;
    let key = '';
    for (let k in playerList) {
        if (playerList[k].uid == id && playerList[k].flag == 0) {
            flag = 1;
            key = k;
            break;
        }
    }
    if (!flag) {
        return this.quick_error('N2BS1', "无法挑战对手");
    }
    //设置对手
    playerList[key].flag = 1;
    await playerRedis.set(this.uid, key, playerList[key]);
    //创建战斗数据
    let ttl = 1 * 24 * 3600 //有效期1天
    await battleCache.set("PVP:" + this.uid, battleData, ttl)
    return;
}


/**
 * @name endBattle
 * @param int result 是否胜利
 * 结束战斗
 */
exports.endBattle = async function () {
    let res = this.get('result', 'int') || 0;
    let battleCache = this.model.redis("battleCache", this.sid);
    let redisData = await battleCache.get("PVP:" + this.uid);
    let arenaConfig = this.config('arenaConfig', seasonID);
    if (!arenaConfig) {
        return this.quick_error("M2saghge40", "竞技场数据不存在", seasonID);
    }
    let playerRedis = this.model.redis("ladder/player", this.sid);
    let playerList = await playerRedis.get(this.uid);
    let key = '';
    for (let k in playerList) {
        if (playerList[k].uid == redisData.battleUid && playerList[k].flag < 2) {
            key = k;
            break;
        }
    }
    if (key == '') {
        return this.quick_error('N2BS1', "战斗已经结算过了");
    }
    this.updater.record.add(34, 1);
    this.updater.daily.add("record.34", 1);
    if (res == 0) {
        //失败
        let ret1 = await this.library("rank/update3V3", this.uid, arenaConfig.loseScore);

        this.updater.role.set("pvpS.score", parseInt(ret1));
        let playerRedisSort = this.model.redis("sort", this.sid, "PvP_3V3_Sort");
        // let score = await playerRedisSort.incr(this.uid, 50);
        let rank = await playerRedisSort.get(this.uid);
        this.updater.role.set("pvpS.rank", parseInt(rank));
        // await this.updater.save();
        playerList[key].flag = 1;
        await playerRedis.set(this.uid, key, playerList[key]);
        //还要给对手发送防守成功奖励邮件,现在不发了
        // let mail = this.model.mongo('mail', this.sid);
        // let data = { "title": "防守成功邮件", "content": "防守成功邮件内容" };
        //给防守成功的奖励
        // if(attr && attr.indexOf(',') > 0){
        // data['attr'] = '1,' + arenaConfig.winItem + ',1';
        // }
        //判断是不是机器人，机器人不用发
        //判断每日获取防守奖励的上限，这个写到redis里面
        // mail.add(redisData.battleUid, data);
        if (arenaConfig.loseItem) {
            let { err, ret } = this.updater.item.group(arenaConfig.loseItem, 1);
            if (err) {
                return this.error(err, ret);
            }
            await this.updater.save();
            return { "playerList": playerList[key], "reward": ret }
        } else {
            return { "playerList": playerList[key], "reward": [] }
        }
    } else {
        //计算段位，是否达到本赛季最高段位
        this.updater.role.key('pvpS.score');
        this.updater.role.key('pvpS.maxRank');
        this.updater.role.key('pvpS.maxScore');
        await this.updater.data();
        let ret1 = await this.library("rank/update3V3", this.uid, arenaConfig.winScore);
        this.updater.role.set("pvpS.score", parseInt(ret1));
        let playerRedisSort = this.model.redis("sort", this.sid, "PvP_3V3_Sort");
        // let score = await playerRedisSort.incr(this.uid, 50);
        let rank = await playerRedisSort.get(this.uid);
        this.updater.role.set("pvpS.rank", parseInt(rank));
        // let score=parseInt(ret)//this.updater.role.get('pvp.score');
        //加分策略待定
        // score+=20;
        let maxRank = this.updater.role.get('pvpS.maxRank');
        if (maxRank > parseInt(rank)) {
            this.updater.role.set("pvpS.maxRank", parseInt(rank));
            //判断是不是要领取本赛季最高段位

        }
        let maxScore = this.updater.role.get('pvpS.maxScore');
        if (maxScore < ret1) {
            this.updater.record.max(35, parseInt(ret1));
            this.updater.role.set("pvpS.maxScore", parseInt(ret1));
        }
        if (arenaConfig.winItem) {
            let { err, ret } = this.updater.item.group(arenaConfig.winItem, 1);
            if (err) {
                return this.error(err, ret);
            }
            this.updater.record.add(55, 1);
            await this.updater.save();
            playerList[key].flag = 2;
            await playerRedis.set(this.uid, key, playerList[key]);
            return { "playerList": playerList[key], "reward": ret }
        } else {
            this.updater.record.add(55, 1);
            await this.updater.save();
            playerList[key].flag = 2;
            await playerRedis.set(this.uid, key, playerList[key]);
            return { "playerList": playerList[key], "reward": [] }
        }
    }
}


/**
 * @name getRank
 * @param string uid 对手ID,用逗号分隔
 * 获取排名
 */
exports.getRank = async function () {
    let idList = this.get('uid', 'string').split(',');
    if (idList.length < 1) {
        return this.quick_error('M2saghge140', '参数错误');
    }
    let playerRedisSort = this.model.redis("sort", this.sid, "PvP_3V3_Sort");
    let data = {};
    for (let i = 0; i < idList.length; i++) {
        let rank = await playerRedisSort.get(idList[i]);
        data[idList[i]] = rank;
    }

    return data;
}

/**
 * @name getWeekReward
 * 获取每周奖励
 */
exports.getWeekReward = async function () {
    //判断赛季是否开放
    const arena3V3SeasonStart = this.config('base', 'arena3V3SeasonStart').strVal;
    const arena3V3RoundTime = this.config('base', 'arena3V3RoundTime').val; // 赛季战斗时长，单位小时
    const arena3V3ResultTime = this.config('base', 'arena3V3ResultTime').val; // 赛季结算时长，单位小时
    let { beginTIme, endTIme, currentSeason } = getSeasonTimes(arena3V3SeasonStart, arena3V3RoundTime, arena3V3ResultTime);
    if (this.updater.time < endTIme) {
        return this.quick_error("M2saghge40", "竞技场赛季未结算", seasonID);
    }
    //判断是否在周结算阶段
    //arenaRankConfig 奖励表
    this.updater.role.key("pvpS");
    await this.updater.data();
    let pvpData = this.updater.role.get("pvpS");
    if (!pvpData) {
        return this.quick_error("M2saghge40", "数据不存在", pvpData);
    }
    const seasonRewardConfig = this.config("arenaRankConfig", seasonID);
    if (!seasonRewardConfig) {
        return this.quick_error("M2saghge40", "竞技场赛季奖励数据不存在", "arenaRankConfig", seasonID);
    }
    let score = pvpData.score;
    // await this.updater.daily.model.week(dkey);
    let weekTime = this.library("time/week");
    let week = this.library("time/sign", weekTime);
    if (pvpData.week >= week) {
        return this.quick_error("M2saghge40", "周奖励已领取", week);
    }
    for (let i in seasonRewardConfig.Coll) {
        if (seasonRewardConfig.Coll[i].rankStart <= score && seasonRewardConfig.Coll[i].rankEnd > score) {
            this.updater.add(seasonRewardConfig.Coll[i].weeklyReward, 1);
            this.updater.role.set("pvpS.week", week);
            // if (seasonRewardConfig.Coll[i].rankDown != 0) {
            //     this.updater.role.set("pvpS.score", seasonRewardConfig.Coll[i].rankDown);
            // }
            break;
        }
    }
    return this.updater.save();
}


/**
 * @name getSeasonReward
 * 获取赛季奖励
 */
exports.getSeasonReward = async function () {
    //判断赛季是否开放
    const arena3V3SeasonStart = this.config('base', 'arena3V3SeasonStart').strVal;
    const arena3V3RoundTime = this.config('base', 'arena3V3RoundTime').val; // 赛季战斗时长，单位小时
    const arena3V3ResultTime = this.config('base', 'arena3V3ResultTime').val; // 赛季结算时长，单位小时
    let { beginTIme, endTIme, currentSeason } = getSeasonTimes(arena3V3SeasonStart, arena3V3RoundTime, arena3V3ResultTime);
    if (this.updater.time < endTIme) {
        return this.quick_error("M2saghge40", "竞技场赛季未结算", seasonID);
    }
    //arenaRankConfig 奖励表
    this.updater.role.key("pvpS");
    await this.updater.data();
    let pvpData = this.updater.role.get("pvpS");
    if (!pvpData) {
        return this.quick_error("M2saghge40", "数据不存在", pvpData);
    }
    const seasonRewardConfig = this.config("arenaRankConfig", seasonID);
    if (!seasonRewardConfig) {
        return this.quick_error("M2saghge40", "竞技场赛季奖励数据不存在", "arenaRankConfig", seasonID);
    }
    let score = pvpData.score;
    if (pvpData.ID > currentSeason) {
        return this.quick_error("M2saghge40", "赛季奖励已领取", seasonID);
    }
    for (let i in seasonRewardConfig.Coll) {
        if (seasonRewardConfig.Coll[i].rankStart <= score && seasonRewardConfig.Coll[i].rankEnd > score) {
            this.updater.add(seasonRewardConfig.Coll[i].seasonReward, 1);
            // this.updater.role.set("pvpS", pvpData);
            let playerRedisSort = this.model.redis("sort", this.sid, "PvP_3V3_Sort");

            this.updater.role.set("pvpS", { "ID": pvpData.ID + 1, "score": 0, "rank": 0, "defend": 0, "week": 0, "maxScore": 0, "maxRank": 0 });
            break;
        }
    }
    let ret1 = await this.library("rank/reset3V3", this.uid);
    console.log('rest ret:', ret1);
    return this.updater.save();
}


// function getSeasonTimes(arena3V3SeasonStart, arena3V3RoundTime, arena3V3ResultTime) {
//     let beginTime, endTime;
//     let currentSeason; // 添加变量来存储当前是第几次循环
//     const seasonStartTime = new Date(arena3V3SeasonStart).getTime();
//     const currentTime = Date.now();
//     const fullSeasonTime = (arena3V3RoundTime + arena3V3ResultTime) * 24 * 3600000; // 转换小时到毫秒
//     // 计算当前时间处于第几个赛季
//     const seasonNumber = Math.floor((currentTime - seasonStartTime) / fullSeasonTime);
//     //判断现在是arena3V3RoundTime还是 arena3V3ResultTime
//     // 计算当前赛季的开始时间和结束时间
//     beginTime = new Date(seasonStartTime + fullSeasonTime * seasonNumber);
//     endTime = new Date(beginTime.getTime() + arena3V3RoundTime * 3600000);
//     currentSeason = seasonNumber + 1; // 当前是第几次循环
//     const cycleTime = arena3V3RoundTime + arena3V3ResultTime; // 一个循环的总时间


//     return { beginTime, endTime, currentSeason };
// }


function getSeasonTimes(arena3V3SeasonStart, arena3V3RoundTime, arena3V3ResultTime) {
    const seasonStartTime = new Date(arena3V3SeasonStart).getTime();
    const currentTime = Date.now();
    const fullSeasonTime = (arena3V3RoundTime + arena3V3ResultTime) * 24 * 3600000; // 转换小时到毫秒
    const seasonNumber = Math.floor((currentTime - seasonStartTime) / fullSeasonTime);
    const currentCycleStartTime = seasonStartTime + fullSeasonTime * seasonNumber;
    const battleEndTime = currentCycleStartTime + arena3V3RoundTime * 24 * 3600000;
    const cycleEndTime = currentCycleStartTime + fullSeasonTime;
    const currentSeason = seasonNumber + 1; // 当前是第几次循环

    let phase, beginTime, endTime;
    if (currentTime < battleEndTime) {
        phase = 1;
        beginTime = new Date(currentCycleStartTime);
        endTime = new Date(battleEndTime);
    } else {
        phase = 0;
        beginTime = new Date(battleEndTime);
        endTime = new Date(cycleEndTime);
    }

    return { beginTime, endTime, currentSeason, phase };
}


//扫描排行榜发送邮件奖励
// /**
//  * @name getDailyReward
//  * 获取每日奖励
//  */
// exports.getDailyReward = async function () {
//     //判断赛季是否开放
//     const seasonConfig = this.config("arenaSeason", seasonID);
//     if (!seasonConfig) {
//         return this.quick_error("M2saghge40", "竞技场赛季数据不存在", seasonID);
//     }
//     let { beginTIme, endTIme, currentSeason } = getSeasonTimes();
//     if (this.updater.time < beginTIme || this.updater.time > endTIme) {
//         return this.quick_error("M2saghge40", "竞技场赛季未开放", seasonID);
//     }
//     //arenaRankConfig 奖励表
//     this.updater.role.key("pvpS");
//     await this.updater.data();
//     let pvpData = this.updater.role.get("pvpS");
//     if (!pvpData) {
//         return this.quick_error("M2saghge40", "数据不存在", pvpData);
//     }
//     const seasonRewardConfig = this.config("arenaRankConfig", seasonID);
//     if (!seasonRewardConfig) {
//         return this.quick_error("M2saghge40", "竞技场赛季奖励数据不存在", "arenaRankConfig", seasonID);
//     }
//     let score = pvpData.score;
//     let todayTime = this.library("time/today");
//     let today = this.library("time/sign", todayTime);
//     if (pvpData.daily >= today) {
//         return this.quick_error("M2saghge40", "今日奖励已领取", today);
//     }
//     for (let i in seasonRewardConfig.Coll) {
//         if (seasonRewardConfig.Coll[i].rankStart <= score && seasonRewardConfig.Coll[i].rankEnd > score) {
//             this.updater.add(seasonRewardConfig.Coll[i].dailyReward, 1);
//             this.updater.role.set("pvpS.daily", today);
//             break;
//         }
//     }
//     return this.updater.save();
// }
